<?php
namespace Admin\Model;

use Think\Model;

class CertificatePeriodModel extends Model
{
    protected $connection = 'XYC';
    protected $trueTableName = 'certificate_period';
    protected $_validate = array(
        array('numbering', 'require', '订单号不能为空'),
        array('numbering', 'check_numbering', '请先确认之前的续期订单','0','callback'),
        array('numbering', 'check_certificate', '凭证状态异常，无法续期','0','callback'),
        array('lender_id', 'require', '出借人不能为空'),
        array('shop_idenfier', 'require', '商户号不能为空'),
        array('borrower_id', 'require', '借款人不得为空'),
        array('money', 'check_number', '本金不能小于等于0','0','callback'),
//        array('interest', 'check_number', '利息不能小于等于0','0','callback'),
//        array('interest_rate', 'check_number', '年利率不能小于等于0','0','callback'),
        array('repayment_time', 'require', '原还款日期不能为空'),
        array('period_time', 'require', '展期日期不能为空'),
        array('period_days', 'check_number', '展期天数不能小于等于0','0','callback'),
    );

    /**
     * @param int $param
     * @return bool
     */
    public function check_number($param){
        if($param<0){
            return false;
        }else{
            return true;
        }
    }

    public function check_numbering($param){
        $res=$this->WHERE(['numbering'=>$param,'status'=>'1'])->getField('id');
        if(!empty($res)){
            return false;
        }else{
            return true;
        }
    }

    public function check_certificate($param){
        $res=D('Certificate')->WHERE(['numbering'=>$param,'status'=>['in',['2','3','4','9']]])->getField('id');
        if(!empty($res)){
            return true;
        }else{
            return false;
        }
    }

    protected function _before_insert(&$data,$option){
        $certificate_db=new CertificateModel();
        $msg=$certificate_db->WHERE(['numbering'=>$data['numbering']])->FIND();
        $data['lender_id']=$msg['lender_id'];
        $data['borrower_id']=$msg['borrower_id'];
        $data['money']=$msg['money'];
    }

    protected function _after_insert($data,$option){
//        $certificate_db=new CertificateModel();
//        $msg=$certificate_db->WHERE(['numbering'=>$data['numbering']])->FIND();
//        switch($msg['status']){
//            case '3'://已逾期
//                if($data['period_time']<strtotime(date('Y-m-d'))){
//                    $certificate_db->WHERE(['numbering'=>$data['numbering']])->setField('status','3');
//                }else{
//                    $certificate_db->WHERE(['numbering'=>$data['numbering']])->setField('status','4');
//                }
//                break;
//            case '4'://已续借
//                break;
//            case '9'://已打款
//                $certificate_db->WHERE(['numbering'=>$data['numbering']])->setField('status','4');
//                break;
//        }
//        $certificate_db->WHERE(['numbering'=>$data['numbering']])->setField('period_time',$data['period_time']);
    }

}